package com.xxl.job.executor.service.jobhandler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.sjbank.mapper.*;
import com.xxl.job.executor.sjbank.pojo.*;
import com.xxl.job.executor.sjbank.pojo.model.CrdCmdResVo;
import com.xxl.job.executor.sjbank.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

@Component
public class CaseXxlJob {
    @Resource
    FiCreditcasesMapper fiCreditcasesMapper;
    @Resource
    CfgActivityService cfgActivityService;
    @Resource
    CfgAssignsetService cfgAssignsetService;
    @Resource
    FiStopcallService fiStopcallService;
    @Resource
    FiAmortDetailService fiAmortDetailService;
    @Resource
    FiCreditcasesHistService fiCreditcasesHistService;
    @Resource
    ConCustomerService conCustomerService;
    @Resource
    FiCreditcasesService fiCreditcasesService;
    @Resource
    FiStopcallMapper fiStopcallMapper;
    @Resource
    ExecutorServiceImpl executorService;
    @Resource
    CreditAccountEventDtlService creditAccountEventDtlService;

    @Value("${billys.url}")
    private String billYsUrl;

    @Value("${yetbilltl.url}")
    private String yetTlUrl;

    @Value("${notbilltl.url}")
    private String notTlUrl;

    @Value("${acctbal.url}")
    private String acctBalUrl;

    @Value("${yinshu.url}")
    private String yinShuAcctUrl;

    @XxlJob("demoJobHandler")
    public void demoJobHandler() {
        executorService.syncBusinessTaskExecutor("tab1");
        executorService.syncBusinessTaskExecutor("tab2");
    }


    /**
     * 分发中间表到业务表
     */
    @XxlJob("syncBill")
    public void syncBill() {
        try {
            conCustomerService.syncCustInfo();
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB-syncCredit, 错误日志:" + e);
        }
    }

    /**
     * 分发联系人
     */
    @XxlJob("syncContact")
    public void syncContact() {
        try {
            conCustomerService.syncContact();
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB-syncContact, 错误日志:" + e);
        }
    }

    /**
     * 分发信用卡已出/未出账单流水表）
     */
    @XxlJob("syncEventDt")
    public void syncEventDt() {
        creditAccountEventDtlService.syncEventDtl();
    }

    /**
     * 生成案件
     */
    @XxlJob("generateCase")
    public void generateCase() {
        try {
            fiCreditcasesService.generateCase();
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB-generateCase, 错误日志:" + e);
        }
    }

    /**
     * 自动分案
     */
    @XxlJob("autoDistribute")
    public void autoDistribute() {
        try {
            XxlJobHelper.log("XXL-JOB, autoDistribute.自动分案开始.");
            cfgActivityService.autoDistribute();
            XxlJobHelper.log("XXL-JOB, autoDistribute.自动分案结束.");
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB, autoDistribute.错误日志:" + e);
        }
    }

    /**
     * 自动派工
     */
    @XxlJob("autoAssign")
    public void autoAssign() {
        try {
            XxlJobHelper.log("XXL-JOB, autoAssign.自动派工开始.");
            cfgAssignsetService.autoAssign();
            XxlJobHelper.log("XXL-JOB, autoAssign.自动派工结束.");
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB, autoAssign.错误日志:" + e);
        }
    }

    /**
     * 回收案件
     */
    @XxlJob("recyclingCase")
    public void recyclingCase() {
        try {
            XxlJobHelper.log("XXL-JOB, recyclingCase.回收案件开始.");
            fiCreditcasesService.recyclingCase();
            XxlJobHelper.log("XXL-JOB, recyclingCase.回收案件结束.");
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB, recyclingCase.错误日志:" + e);
        }
    }

    /**
     * 解除停催
     */
    @XxlJob("stopCall")
    public void stopCall() {
        try {
            fiStopcallService.stopCall();
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB, stopCall.错误日志:" + e);
        }
    }

    /**
     * 协商分期是否还款
     */
    @XxlJob("checkAmort")
    public void checkAmort() {
        try {
            XxlJobHelper.log("XXL-JOB, checkAmort协商分期是否还款开始.");
            fiAmortDetailService.checkAmort();
            XxlJobHelper.log("XXL-JOB, checkAmort协商分期是否还款结束.");
        } catch (Exception e) {
            XxlJobHelper.log("XXL-JOB, checkAmort.错误日志:" + e);
        }
    }

    /**
     * AI名单推送
     */
    @XxlJob("aiPush")
    public void aiPush() {
        XxlJobHelper.log("XXL-JOB, aiPush.AI名单推送开始.");
        fiCreditcasesService.aiPush();
        XxlJobHelper.log("XXL-JOB, aiPush.AI名单推送结束.");

    }

    /**
     * 案件出催
     */
    @XxlJob("closeCase")
    public void closeCase() {
        long cCount = 1;
        if (cCount > 0) {
            XxlJobHelper.log("XXL-JOB-closeCase 案件出催开始");
            CrdCmdResVo resVo = new CrdCmdResVo();

            List<FiCreditcases> list = fiCreditcasesMapper.selectList(new LambdaQueryWrapper<FiCreditcases>()
                    .ne(FiCreditcases::getStatus, 9)
                    .eq(FiCreditcases::getOdudPrin, 0)
            );

            XxlJobHelper.log("XXL-JOB-closeCase 待刷新出催案件:" + list.size() + "条.");
            int okcount = 0, rpccount = 0;

            for (FiCreditcases x : list) {
                try {
                    okcount++;
                    DoUpdateCase(x.getCreditcaseid(), x.getCollectno());
                    rpccount++;
                } catch (Exception e) {
                    XxlJobHelper.log("XXL-JOB-closeCase 输出错误日志:{} >>>>>【异常列】:{}", e, x);
                }
            }

            resVo.setRpccount(rpccount);
            resVo.setTotal(list.size());
            resVo.setOkcount(okcount);
            resVo.setRespCode("0");
            resVo.setRespCodeDesc("success");
            XxlJobHelper.log("XXL-JOB-closeCase 执行结果,刷新案件总数:{}；刷新案件成功总数:{}；出催数量:{}", resVo.getTotal(), resVo.getOkcount(), resVo.getRpccount());
        } else {
            XxlJobHelper.log("XXL-JOB-closeCase 出催Job不执行,最新T+1逾期天数表数量为:{}", cCount);
        }
    }
    
    private void DoUpdateCase(Integer ficaseid, String collectno) {//案件出催
        try {
            FiCreditcases fi = new FiCreditcases();
            fi.setCreditcaseid(ficaseid);
            fi.setCollectno(collectno);
            fi.setStatus(9);
            fi.setStatusdt(new Date());
            fi.setCcc("R");
            fi.setCloseusr("system");
            fi.setClosedt(new Date());
            fi.setMdusr("system");
            fi.setMddt(new Date());
            fi.setAppointdt(null);
            fiCreditcasesService.updateById(fi);

            FiCreditcases fiCase = fiCreditcasesMapper.selectOne(new QueryWrapper<FiCreditcases>().eq("collectno", collectno));
            XxlJobHelper.log("DoUpdateCase:" + fi + "fiCase:" + fiCase);
            FiCreditcasesHist fiCreditcasesHist = new FiCreditcasesHist();
            // 将属性复制到新对象中
            BeanUtils.copyProperties(fiCase, fiCreditcasesHist);
            fiCreditcasesHistService.save(fiCreditcasesHist);
        } catch (Exception e) {
            //e.printStackTrace();
            XxlJobHelper.log("DoUpdateCase输出错误:" + e);
        }
    }
    
    private BigDecimal getPayAmount(Integer ficaseid) {//取实际还款额
        try {
            FiCreditcases fi = fiCreditcasesMapper.selectById(ficaseid);
            String acctno = fi.getCreditAcct();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //开始时间从分案次日凌晨开始，在函数里面计算
            String distdt = sdf.format(fi.getDistdt());
            String recydt = sdf.format(new Date());
            return fiStopcallMapper.getPayAmount(acctno, distdt, recydt);
        } catch (Exception e) {
            XxlJobHelper.log("getPayAmount({}).Fail:{}", ficaseid, e.getMessage());
            return new BigDecimal(100.0);
        }
    }
}